package day03;

import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Demo04 {
    @Test
    public void insert()throws Exception{
        Connection connection = JDBCUtils.getConnection();
        String sql = "INSERT INTO `user` (username,password) VALUES (?,?);";
        PreparedStatement pst = connection.prepareStatement(sql);
        //为sql语句中的?赋值
        pst.setObject(1,"tianqi");
        pst.setObject(2,"999");
        pst.executeUpdate();
        JDBCUtils.close(connection,pst,null);
    }

    @Test
    public void delete()throws Exception{
        Connection connection = JDBCUtils.getConnection();
        String sql = "delete from user where uid = ?";
        PreparedStatement pst = connection.prepareStatement(sql);
        //为sql语句中的?赋值
        pst.setObject(1,2);
        pst.executeUpdate();
        JDBCUtils.close(connection,pst,null);
    }

    @Test
    public void update()throws Exception{
        Connection connection = JDBCUtils.getConnection();
        String sql = "update user set password = ? where uid = ?";
        PreparedStatement pst = connection.prepareStatement(sql);
        //为sql语句中的?赋值
        pst.setObject(1,"111");
        pst.setObject(2,3);
        pst.executeUpdate();
        JDBCUtils.close(connection,pst,null);
    }

    @Test
    public void query()throws Exception{
        Connection connection = JDBCUtils.getConnection();
        String sql = "select username,password from user where uid = ?";
        PreparedStatement pst = connection.prepareStatement(sql);
        //为sql语句中的?赋值
        pst.setObject(1,4);
        ResultSet resultSet = pst.executeQuery();
        while (resultSet.next()){
            String username = resultSet.getString("username");
            String password = resultSet.getString("password");
            System.out.println(username+"--"+password);
        }
        JDBCUtils.close(connection,pst,resultSet);
    }
}
